package org.saxonextensions.eml.dispatcher.jboss;

import org.jboss.logging.Logger;
import org.saxonextensions.eml.dispatcher.AbstractThreadedEMLDispatcher;

import javax.mail.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.Serializable;

/**
 * Threaded EML Dispatcher implementation.
 * Received message is added to a thread pool runner that dispatch it to the destination server.
 * When thread pool is exhausted this thread is paused for 500ms.
 *
 * @author Ivan Latysh
 * @since 7-Feb-2009 5:15:55 PM
 */
public class ThreadedEMLDispatcherImpl extends AbstractThreadedEMLDispatcher implements EMLDispatcherRemote, Serializable {

  /** Logger */
  protected transient Logger logger = Logger.getLogger(this.getClass());
  /** Mail service JNDI name */
  protected String mailServiceJndiName;
  /** Context */
  protected Context ctx;  

  /**
   * Return mail service JNDI name
   *
   * @return JNDI name
   */
  public String getMailServiceJndiName() {
    return mailServiceJndiName;
  }

  /**
   * Set mail service JNDI name
   *
   * @param mailServiceJndiName JNDI name
   */
  public void setMailServiceJndiName(String mailServiceJndiName) {
    this.mailServiceJndiName = mailServiceJndiName;
  }

  /**
   * Stop dispatching
   */
  public void stop() {
    logger.info("Stopping dispatcher.");
    logger.info("Dispatcher stopped.");
  }

  /**
   * Start dispatching
   */
  public void start() {
    logger.info("Starting dispatcher.");
    logger.info("Dispatcher started.");
  }

  /**
   * Destroy dispatcher
   */
  public void destroy() {
    logger.info("Destroying dispatcher.");
    super.destroy();
    logger.info("Dispatcher destroyed.");
  }

  /**
   * Lookup and return a new Mail Session
   *
   * @return Mail Session
   * @throws javax.naming.NamingException when unable to lookup a session
   * @throws IllegalStateException when found session is null, or can not be cast to {@link javax.mail.Session}
   */
  public Session getSession() throws NamingException, IllegalStateException {
    if (null==ctx) {
      ctx = new InitialContext();
    }
    Object mailSessionObject = ctx.lookup(mailServiceJndiName);
    if (null==mailSessionObject) {
      throw new IllegalStateException("Returned Mail Session {"+mailServiceJndiName+"} is null.");
    }
    if (!(mailSessionObject instanceof Session)) {
      throw new IllegalStateException("Unable to cast {"+mailSessionObject.getClass().getName()+"} to {"+Session.class.getName()+"}.");
    }
    // return session
    return (Session)mailSessionObject;
  }

}
